<!-- Admin Manage -->
<template>
  <v-container>
    <v-data-table
    dense
    must-sort
    item-key="id"
    show-select
    v-model="tableSelected"
    :headers="tableHeaders"
    :items="tableItems"
    :options.sync="tableOptions"
    :loading="tableLoading"
    :server-items-length="tableItemsTotal"
        :footer-props="{
          showFirstLastPage: true,
          showCurrentPage: true,
          itemsPerPageOptions: [5, 20, 30, 50]
        }">
    <template v-slot:top>
        <v-row  no-gutters dense>
          <v-col cols="12">
            <v-btn text color="accent" @click="fetchData"><v-icon >refresh</v-icon>刷新</v-btn>
            <v-btn text color="primary" @click="btnAdd"><v-icon>add</v-icon>新增</v-btn>
            <v-btn text color="error" :disabled="tableSelected.length <= 0" @click="deleteItemHandle(tableSelected)"><v-icon >close</v-icon>删除</v-btn>
            <v-divider></v-divider>
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="12" sm="9">
            <v-form ref="searchField">
              <v-row no-gutters>
                <v-col cols="12" sm="5">
                  <v-select
                  :items="searchFieldItems"
                  prepend-icon="text_fields"
                  label="搜索字段"
                  solo-inverted
                  flat
                  dense
                  v-model="tableSearchField.field"></v-select>
                </v-col>
                <v-col cols="12" sm="7">
                  <v-text-field
                  solo-inverted
                  flat
                  dense
                  label="请输入搜索内容！"
                  prepend-icon="search"
                  v-model="tableSearchField.keyword"></v-text-field>
                  </v-col>
              </v-row>
            </v-form>
          </v-col>
          <v-col cols="12" sm="3">
            <v-btn color="primary" @click="fetchData"><v-icon>search</v-icon>搜索</v-btn>
            <v-btn text @click="$refs.searchField.reset();fetchData()"><v-icon>refresh</v-icon>重置</v-btn>
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="12" sm="2" v-show="tableSelected.length > 0">
            <span>已选中<span class="primary--text font-weight-black">{{tableSelected.length}}</span>条记录</span>
          </v-col>
        </v-row>
      <!-- </v-container> -->
    </template>
    <template v-slot:item.action="{ item }">
      <v-btn icon small text color="info" @click.stop="btnEditItem(item)"><v-icon small>edit</v-icon></v-btn>
      <!-- <v-btn icon small text color="red" @click.stop="deleteItemHandle(item)"><v-icon small>delete</v-icon></v-btn> -->
    </template>
    </v-data-table>
    <v-dialog v-model="formDialog" persistent width="50%">
      <v-card :key="formData.id || 'new'">
        <v-card-title>编辑</v-card-title>
        <v-form ref="adminForm">
          <v-container>
            <v-row>
              <v-col>
                <v-text-field
                required
                label="用户名"
                v-model="formData.username"
                name="username"
                v-validate="'required|max:40'"
                :error-messages="errors.collect('username')"
                data-vv-as="用户名"></v-text-field>
                <v-text-field
                type="password"
                label="密码"
                v-model="formData.password"
                name="password"
                v-validate="{required: mode==='create', min: 6}"
                :append-icon="showPassword ? 'visibility_off' : 'visibility'"
                @click:append="showPassword = !showPassword"
                :error-messages="errors.collect('password')"
                data-vv-as="密码"></v-text-field>
                <v-text-field
                type="password"
                label="密码确认"
                v-model="formData.repassword"
                :append-icon="showRePassword ? 'visibility_off' : 'visibility'"
                 @click:append="showRePassword = !showRePassword"
                name="repassword"
                v-validate="{ required: repasswordRequired  , is: formData.password }"
                :error-messages="errors.collect('repassword')"
                data-vv-as="密码确认"></v-text-field>
                <v-text-field required label="真实姓名" v-model="formData.truename"></v-text-field>
                <v-text-field required type="email" label="邮箱" v-model="formData.email"></v-text-field>
                <v-text-field label="联系方式" v-model="formData.mobile"></v-text-field>
                <v-select
                v-model="formData.role"
                :items="rolesArray"
                label="用户角色"
                chips></v-select>
              <v-select
                v-model="formData.status"
                :items="statusArray"
                label="状态"
                chips
              ></v-select>
              </v-col>
            </v-row>
          </v-container>
        </v-form>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn :loading="formBtnDisabled" :disabled="formBtnDisabled" @click="formDialog = false">取消</v-btn>
          <v-btn :loading="formBtnDisabled" :disabled="formBtnDisabled" class="primary" @click="btnFormDataSubmit">提交</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
import * as API from '@/api/admin/admin.js'
export default {
  name: 'AdminManage',
  components: {},
  data: function () {
    return {
      tableHeaders: [
        { text: 'ID', value: 'id', align: 'center' },
        { text: '用户名', value: 'username', align: 'center' },
        { text: '真实姓名', value: 'truename', align: 'center' },
        { text: 'Email', value: 'Email', align: 'center' },
        { text: '联系方式', value: 'mobile', align: 'center' },
        { text: '角色', value: 'role', align: 'center' },
        { text: '状态', value: 'status', align: 'center' },
        { text: '注册时间', value: 'createdAt', align: 'center' },
        { text: '操作', value: 'action', sortable: false, width: '118px', align: 'center' }
      ],
      tableLoading: false,
      tableItems: [],
      tableOptions: {
        page: 1,
        itemsPerPage: 20,
        sortBy: [ 'id' ],
        sortDesc: [ true ]
      }, // 分页参数
      tableItemsTotal: 0, // 总个数
      tableSearchField: {
        field: '',
        keyword: ''
      },
      tableSelected: [],
      searchFieldItems: [
        { value: 'id', text: 'ID' },
        { value: 'username', text: '用户名' },
        { value: 'truename', text: '真实姓名' },
        { value: 'email', text: '邮箱' },
        { value: 'mobile', text: '联系方式' }
      ],
      formDialog: false,
      formData: {},
      formBtnDisabled: false,
      showPassword: false,
      showRePassword: false,
      rolesArray: [
        { text: '超级管理员', value: 'super-admin' },
        { text: '管理员', value: 'admin' }
      ],
      statusArray: [
        { text: '正常', value: 'normal' },
        { text: '停用', value: 'stop' }
      ]
    }
  },
  watch: {
    tableOptions: {
      handler () {
        this.fetchData()
      },
      deep: true
    }
  },
  computed: {
    mode: function() {
      return this.formData.hasOwnProperty('id') ? 'edit' : 'create'
    },
    repasswordRequired: function() {
      return this.mode === 'create' || this.formData.password !== null
    }
  },
  methods: {
    fetchData: function() {
      this.tableLoading = true
      API.fetchList({
        sort: this.tableOptions.sortBy[0],
        descending: this.tableOptions.sortDesc[0],
        page: this.tableOptions.page,
        page_size: this.tableOptions.itemsPerPage,
        search: this.tableSearchField
      }).then(res => {
        this.tableItems = res.data.data
        this.tableItemsTotal = res.data.total
      }).catch(err => {
        this.$toasted.error(err.message)
      }).finally(() => {
        this.tableLoading = false
        this.tableSelected = []
      })
    },
    btnAdd: function() {
      this.formData = {}
      this.formDialog = true
    },
    btnFormDataSubmit() {
      const submitAPI = this.formData.hasOwnProperty('id') ? API.updateOne : API.createOne
      this.$validator.validate().then(result => {
        if (result) {
          this.formBtnDisabled = true
          submitAPI(this.formData).then(res => {
            this.$toasted.success(res.data)
            this.formDialog = false
            this.fetchData()
          }).finally(() => {
            this.formBtnDisabled = false
          })
        }
      })
    },
    btnEditItem: function(item) {
      this.formData = item
      this.formDialog = true
    },
    deleteItemHandle: function(items) {
      if (confirm('是否确定删除这条数据信息？删除后无法恢复，请慎重！')) {
        API.deleteOne(items.map(e => e.id).join('_')).then(res => {
          // const index = this.tableItems.indexOf(item)
          // this.tableItems.splice(index, 1)
          this.fetchData()
          this.$toasted.success(res.data)
        }).catch(err => {
          this.$toasted.error('删除失败！')
          return Promise.reject(err)
        })
      }
    }
  }
}
</script>
<style scoped>
</style>
